package worker

import (
	"fmt"
	"go_chat/handler"
	"go_chat/logger"
	"go_chat/model"
	"go_chat/util"
	"net"
)
// 用于存储用户ip和连接得映射表

// 消息队列
var MessageQueue = make(chan string, 10000)
// 通过channel来结束协程退出
var QuitChan = make(chan bool)


// 接收客户端连接
func receiveConnect(listener net.Listener){
	for {
		conn, err := listener.Accept()
		util.CheckError(err)
		// 将conn连接以ip为key写入映射表
		addr := conn.RemoteAddr().String()
		model.OnlineConns[addr] = conn
		logStr := "current has connection " + addr
		fmt.Println(logStr)
		logger.GetLogger().Println(logStr)
		// 处理请求信息
		go handler.ProcessInfo(conn, MessageQueue)
	}
}

// 进行信息消费
func consumeMessage(){
	for {
		select {
			case message := <- MessageQueue:
				// 进行消息解析返回:
				handler.DoProcessMessage(message)
			case <- QuitChan:
				break
		}
	}
}

// 统一得接收和发送处理函数
func Worker(listener net.Listener){
	go consumeMessage()
	receiveConnect(listener)
}